package cn.gs.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;



import cn.gs.domain.Customer;
import cn.gs.utils.HibernateUtil;

public class CustomerDaoImpl implements CustomerDao {

	
	Session session = HibernateUtil.openSession();
	Transaction transaction = session.getTransaction();

	public void add(Customer c) {
		transaction.begin();
		session.save(c);		
		transaction.commit();
		session.close();
	}

	public void delete(Long id) {
		transaction.begin();
		Customer c = (Customer) session.get(Customer.class, id);
		session.delete(c);
		transaction.commit();
		session.close();
	}

	public void update(Customer c) {
		transaction.begin();
		session.saveOrUpdate(c);		
		transaction.commit();
		session.close();
	}

	public Customer selectByID(Long id) {
		transaction.begin();	
		Customer c = (Customer) session.get(Customer.class, id);
		transaction.commit();
		session.close();
		return c;
	}

	public List<Customer> selectAll() {				
		transaction.begin();
		List<Customer> list = new ArrayList<Customer>();
		Query query = session.createQuery("from Customer");
		list = query.list();
		transaction.commit();
		session.close();
		return list;
	}
	
	public List<Customer> selectPageCount() {
		transaction.begin();
		Query query = session.createQuery("select count(c) from Customer c");
		List list = query.list();
		transaction.commit();
		session.close();
		return list;
	}	
	public List<Customer>  paging(int page){
		transaction.begin();	
		Query query = session.createQuery("from Customer");
		int i=(page-1)*3;
		query.setFirstResult(i);
		query.setMaxResults(3);
		List<Customer> list = query.list();
		transaction.commit();
		session.close();
		return list;
	}
	
	public List<Customer> selName(String name){
		transaction.begin();
		Query query=session.createQuery("from Customer where cust_name like ?");
		query.setParameter(0, "%"+name+"%");
		List list=query.list();
		Customer c=(Customer) list.get(0);
		transaction.commit();
		session.close();
		return list;		
	}

	
}
